package com.chatsocket.util;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 对话管理器
 * 每一个用户登录对应一个 
 */
public class ChatManager {
	private User currentUser;
	private List<Chat> chats=new CopyOnWriteArrayList<Chat>();
	/**
	 * 创建对某个人的对话
	 * @param threadId userType_userId
	 */
	private Chat createChat(String threadId){
		Chat chat=new Chat();
		chat.setCurrent(currentUser.getUserType()+"_"+currentUser.getId());
		chat.setDestination(threadId);
		chats.add(chat);
		return chat;
	}
	/**
	 * 通过threadId获取Chat
	 */
	private Chat getChatByThreadId(String threadId){
		if(chats==null||chats.size()==0){
			return null;
		}
		if(threadId==null){
			return null;
		}
		for(Chat chat:chats){
			if(threadId.equals(chat.getDestination())){
				return chat;
			}
		}
		return null;
	}
	/**
	 * 通过threadId获取或者初始化Chat
	 */
	public Chat getOrInitChatByThreadId(String threadId){
		Chat chat = getChatByThreadId(threadId);
		if(chat==null){
			chat=createChat(threadId);
		}
		return chat;
	}
	public User getCurrentUser() {
		return currentUser;
	}
	public void setCurrentUser(User currentUser) {
		this.currentUser = currentUser;
	}
}
